#include "tools.h"
#include "constants.h"
#include <QApplication>
#include <QFile>
#include <QStringList>
#include <QTextStream>
#include <QDebug>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDir>

using namespace Constants;
using namespace ToolsSpace;

Tools::Tools(QObject * parent){Q_UNUSED(parent);}

Tools::~Tools(){}

QHash<int,QString> Tools::hashOfConditionDelegateCombo() const
{
    QHash<int,QString> hash;
     hash.insert(CONTAINS,"contient");
     hash.insert(INF,"inf");
     hash.insert(SUP,"sup");
     hash.insert(EQUAL,"egal");
    return hash;
}

QHash<QString,QString> Tools::hashOfTypesOfHeads() const
{
    QHash<QString,QString> hash;
    hash.insert("20030000","Observation");
    hash.insert("20080000","Documents");
    hash.insert("20020100","Ordonnance ajustable");
    hash.insert("20060000","Terrain");
    return hash;
}

QHash<int,QString> Tools::hashIntAndTypesOfHeads() const
{
    QHash<int,QString> hash;
    hash.insert(OBSERVATION,"20030000");
    hash.insert(DOCUMENTS,"20080000");
    hash.insert(ORDONNANCE_AJUSTABLE,"20020100");
    hash.insert(TERRAIN,"20060000");
    return hash;
}

QHash<int,QString> Tools::hashIntAndTypeStringsOfHeads() const
{
    QHash<int,QString> hash;
    hash.insert(OBSERVATION,"Observation");
    hash.insert(DOCUMENTS,"Documents");
    hash.insert(ORDONNANCE_AJUSTABLE,"Ordonnance ajustable");
    hash.insert(TERRAIN,"Terrain");
    return hash;
}

QHash<int,QString> Tools::hashOfConjonctions() const
{
    QHash<int,QString> hash;
    hash.insert(AND,"Et");
    hash.insert(OR,"Ou");
    return hash;
}

QHash<int,QString> Tools::hashOfTokens() const
{
    QHash<int,QString> hash;
    int row = 0;    
    QString docterrainpathfile = qApp->applicationDirPath()+"/../resources/doc/terrain";    
    QFile terrainfile(docterrainpathfile);
    if (!terrainfile.open(QIODevice::ReadOnly))
    {
          qWarning() << __FILE__ << QString::number(__LINE__) << "unable to open file " << docterrainpathfile ;
        }
    QTextStream stream(&terrainfile);
    while (!stream.atEnd())
    {
        QString line = stream.readLine();
        if (line.contains("[")&& line.contains("]"))
        {
              hash.insert(row,line);
              ++row;
            }
        }//while
    return hash;
}

QDateTime Tools::firstDateOfTheMedicalFolder(QString patientGuid)
{
    QDate firstDate(3000,01,01);
    QDateTime firstDateTime(firstDate);
    QSqlDatabase db = QSqlDatabase::database(DRTUXTEST_DB);
    QString tablehead = "RubriquesHead";
    if (!db.tables().contains(tablehead))
        {
              tablehead = "rubriqueshead";
            }    
    QString req = QString("select %1 from %2 where %3 = '%4'").arg("RbDate_Date",tablehead,"RbDate_IDDos",patientGuid);
    QSqlQuery qy(db);
    if (!qy.exec(req))
    {
        qWarning() << __FILE__ << QString::number(__LINE__) << qy.lastError().text() ;
        }
    while (qy.next())
    {
        QString datestr = qy.value(0).toString();
        //qDebug() << __FILE__ << QString::number(__LINE__) << datestr ;
        QDateTime datetime = QDateTime::fromString(datestr,"yyyy-MM-ddThh:mm:ss");
        if (datetime <= firstDateTime && !datetime.isNull())
        {
            firstDateTime = datetime;
            }
        }
    return firstDateTime;
}

QHash<int,QString> Tools::getHashOfTitlesAccordingToChoice(int choice, QString patientGuid, QString userlogin)
{
    enum {RBDATE_NOMDATE = 0, RBDATE_REFBLOBS_PRIMKEY};
    QHash<int,QString> hash;
    int type = -1;
    QString code_heads ;
    //hashIntAndTypesOfHeads()
    switch (choice) {
        case TERRAIN_BOX :
            type = TERRAIN;
            break;
        case DOCUMENTS_BOX :
            type = DOCUMENTS;
            break;
        case OBSERVATIONS_BOX :
            type = OBSERVATION;
            break;
        case PRESCRIPTIONS_BOX :
            type = ORDONNANCE_AJUSTABLE;
            break;
        default :
            break;
        }
    code_heads = hashIntAndTypesOfHeads().value(type);
    qDebug() << __FILE__ << QString::number(__LINE__) << "code_heads" << code_heads ;
    //requete sql
    QSqlDatabase db = QSqlDatabase::database(DRTUXTEST_DB);
    QSqlQuery qy(db);
    QString tablehead = "RubriquesHead";
    if (!db.tables().contains(tablehead))
        {
              tablehead = "rubriqueshead";
            }
    QString req = QString("select %1,%2 from %3 where %4 = '%5'").arg("RbDate_NomDate","RbDate_RefBlobs_PrimKey",tablehead,"RbDate_TypeRub",code_heads);
    req += QString(" and %1 = '%2'").arg("RbDate_IDDos",patientGuid);
    req += QString(" and %1 = '%2'").arg("RbDate_CreateUser",userlogin);
    qDebug() << __FILE__ << QString::number(__LINE__) << req ;
    if (!qy.exec(req))
    {
        qWarning() << __FILE__ << QString::number(__LINE__) << qy.lastError().text() ;
        }
    while (qy.next())
    {
        QString title = qy.value(RBDATE_NOMDATE).toString();
        int idblob = qy.value(RBDATE_REFBLOBS_PRIMKEY).toInt();
        hash.insert(idblob,title);
        }
    return hash;
}

const char * Tools::getStringChosenFromBlob(const QString ref)
{
    QByteArray result;
    QSqlDatabase db = QSqlDatabase::database(DRTUXTEST_DB);
    QString tableblobs = "RubriquesBlobs";
    if (!db.tables().contains(tableblobs))
        {
              tableblobs = "rubriquesblobs";
            }
    QSqlQuery qy(db); 
    QString req = QString("select %1 from %2 where %3 = '%4'").arg("RbDate_DataRub",tableblobs,"RbDate_PrimKey",ref);
    if (!qy.exec(req))
    {
        qWarning() << __FILE__ << QString::number(__LINE__) << qy.lastError().text() ;
        }
    while (qy.next())
    {
        result = qy.value(0).toByteArray();
        }
    const char * resultchar = result.data();
    return resultchar;
}

QString Tools::pathToResources()
{
    return qApp->applicationDirPath()+"/../resources";
}

QString Tools::pathToPersonalDatas()
{
    QString path = qApp->applicationDirPath()+"/../donnees_perso";
    QDir dir(path);
    if (!dir.exists())
    {
        dir.mkdir(path);
        }
    return path;
}
